<template>
    <div class="common-page page-corp-company" v-loading.fullscreen="loading">
        <div class="common-page__head">
            <comp-paths class="route" :paths="['/corp', '/corp/companys', $route.fullPath]"></comp-paths>
            <div class="title" v-if="company">
                <span class="text">{{ company.name }}</span>
                <span class="flag" v-if="company.tag.id">{{ company.tag.name }}</span>
            </div>
            <div class="title" v-else></div>
        </div>
        <comp-tabs class="common-page__head" :tabs="[$route.fullPath, '/corp/company/orders?companyId=' + companyId, '/corp/company/attendances?companyId=' + companyId, '/corp/company/demands?companyId=' + companyId, '/corp/company/products?companyId=' + companyId, '/corp/company/feedbacks?companyId=' + companyId]"></comp-tabs>
        <div class="common-page__body common-form" v-if="company">
            <div class="rows">
                <div class="row row--head">
                    <div class="name">基本信息</div>
                    <div class="value">
                        <span class="button button--edit" @click="setCompany()">编辑</span>
                    </div>
                </div>
                <div class="row">
                    <div class="name">{{ company.typeText }}名称</div>
                    <div class="value">{{ company.name }}</div>
                </div>
                <div class="row">
                    <div class="name">{{ company.typeText }}简介</div>
                    <div class="value">
                        <span class="button" @click="action('company-desc', true)">查看</span>
                    </div>
                </div>
                <div class="row">
                    <div class="name">法定代表人</div>
                    <div class="value">{{ company.owner }}</div>
                </div>
                <div class="row">
                    <div class="name">{{ company.typeText }}规模</div>
                    <div class="value">{{ company.sizeText }}</div>
                </div>
                <div class="row">
                    <div class="name">所在地区</div>
                    <div class="value">{{ company.city.name + company.county.name }}</div>
                </div>
                <div class="row">
                    <div class="name">详细地址</div>
                    <div class="value">
                        <span class="text">{{ company.location.address }}</span>
                        <a class="button" :href="company.location.link" target="_blank" v-if="company.location.lng > 0 && company.location.lat > 0">查看</a>
                    </div>
                </div>
                <div class="row">
                    <div class="name">所属行业</div>
                    <div class="value">
                        <span v-for="(item,index) in company.corpIdSysIndustryList">
                            {{(index > 0?',':'')+item.name}}
                        </span>
                    </div>
                </div>
                <div class="row">
                    <div class="name">所属分类</div>
                    <div class="value">{{ company.tag.name }}</div>
                </div>
                <div class="row">
                    <div class="name">资格认定</div>
                    <div class="value">
                        <span class="text" v-if="company.cert01 === 'yes'">高新技术企业</span>
                        <span class="text" v-if="company.cert02 === 'yes'">单项冠军企业</span>
                        <span class="text" v-if="company.cert03 === 'yes'">国家级专精特新小巨人企业</span>
                        <span class="text" v-if="company.cert04 === 'yes'">自治区级专精特新小巨人企业</span>
                        <span class="text" v-if="company.cert05 && company.cert05 !== 'not'">制造业创新中心（{{ company.cert05Text }}）</span>
                        <span class="text" v-if="company.cert06 && company.cert06 !== 'not'">企业技术中心（{{ company.cert06Text }}）</span>
                    </div>
                </div>
                <!-- <div class="row">
                    <div class="name" style="height: auto; min-height: 20px">主管工作队</div>
                    <div class="value">
                        <span class="text" v-for="dept in company.depts" :key="dept.id">{{ dept.name }}</span>
                    </div>
                </div> -->
                <div class="row">
                    <div class="name">最近走访</div>
                    <div class="value">
                        <span v-if="company.attendances.length > 0">{{ company.attendances[0].client.name }}</span>
                        <span style="margin-left: 0.5em; color: #aaa" v-if="company.attendances.length > 0">{{ company.attendances[0].startAt }}</span>
                    </div>
                </div>
                <div class="row">
                    <div class="name">事项统计</div>
                    <div class="value">
                        <span>共 {{ company.stats.ordersTotal }} 项</span>
                        <span style="margin-left: 0.5em; color: #aaa">未办结 {{ company.stats.ordersFinishedNotTotal }} 项</span>
                    </div>
                </div>
                <div class="row">
                    <div class="name">审核状态</div>
                    <div class="value">
                        <span class="text">
                            <span class="el-status--warning" v-if="company.status === 'approving'"></span>
                            <span class="el-status--success" v-else-if="company.status === 'approved'"></span>
                            <span class="el-status--danger" v-else-if="company.status === 'unapproved'"></span>
                            <span>{{ company.statusText }}</span>
                        </span>
                    </div>
                </div>
                <div class="row">
                    <div class="name">添加时间</div>
                    <div class="value">{{ company.createdAt }}</div>
                </div>
                <!-- <div class="row">
                    <div class="name">服务小组</div>
                    <div class="value">{{ company.fwxz }}</div>
                </div> -->
                <div class="row">
                    <div class="name">社会信用代码：</div>
                    <div class="value">{{ company.xydm }}</div>
                </div>
                <div class="row">
                    <div class="name">企业性质：</div>
                    <div class="value">{{ company.qyxz }}</div>
                </div>
                <div class="row row--picture">
                    <img class="value" :src="company.logo" v-if="company.logo" />
                    <img class="value" :src="require('../assets/company-avatar.png')" v-else />
                </div>
            </div>
            <div class="rows">
                <div class="row row--head">
                    <div class="name">联系人信息</div>
                    <div class="value">
                        <span class="button button--add" @click="addCompanyStaff()">添加</span>
                    </div>
                </div>
                <div class="row row--2x">
                    <div class="value">
                        <el-table size="medium" border :data="company.staffs">
                            <el-table-column label="姓名/手机号" min-width="8">
                                <template #default="scope">
                                    <a :href="'#/org/client?clientId=' + scope.row.client.id" v-if="access('org')">{{ scope.row.client.name }}</a>
                                    <span v-else>{{ scope.row.client.name }}</span>
                                    <span style="margin-left: 0.5em; color: #aaa">{{ scope.row.client.mobile }}</span>
                                </template>
                            </el-table-column>
                            <el-table-column label="职务" min-width="6">
                                <template #default="scope">{{ scope.row.duty }}</template>
                            </el-table-column>
                            <el-table-column label="操作" width="160">
                                <template #default="scope">
                                    <el-button type="danger" size="mini" @click.stop="delCompanyStaff(scope.row)">删除</el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </div>
                </div>
            </div>
            <div class="rows">
                <div class="row row--head">
                    <div class="name">服务专员</div>
                    <div class="value">
                        <span class="button button--add" @click="addCompanyHolder()">添加</span>
                    </div>
                </div>
                <div class="row row--2x">
                    <div class="value">
                        <el-table size="medium" border :data="company.holders">
                            <el-table-column label="姓名/手机号" min-width="8">
                                <template #default="scope">
                                    <a :href="'#/org/client?clientId=' + scope.row.client.id" v-if="access('org')">{{ scope.row.client.name }}</a>
                                    <span v-else>{{ scope.row.client.name }}</span>
                                    <span style="margin-left: 0.5em; color: #aaa">{{ scope.row.client.mobile }}</span>
                                </template>
                            </el-table-column>
                            <el-table-column label="所属部门及担任职务" min-width="16">
                                <template #default="scope">
                                    <div v-for="depment in scope.row.client.depments" :key="depment.id">
                                        <span>{{ depment.dept.name }}</span>
                                        <span> - </span>
                                        <span>{{ depment.duty }}</span>
                                    </div>
                                </template>
                            </el-table-column>
                            <el-table-column label="操作" width="160">
                                <template #default="scope">
                                    <el-button type="danger" size="mini" @click.stop="delCompanyHolder(scope.row)">删除</el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </div>
                </div>
            </div>
        </div>

        <comp-dialog title="企业/项目简介" width="600px" height="80vh" ref="companyDesc">
            <comp-html-editor style="height: 100%" ref="companyDescEditor" :content="company.desc" v-if="company">
                <template #foot="scope">
                    <el-button type="plain" size="small" icon="el-icon-close" @click="action('company-desc', false)">关闭</el-button>
                </template>
            </comp-html-editor>
        </comp-dialog>
        <comp-dialog title="编辑基本信息" ref="companySetForm">
            <el-form size="small" label-width="140px" style="margin-right: 20px" @submit.native.prevent v-if="companySetForm">
                <el-form-item label="企业/项目LOGO：">
                    <img style="display: block; margin: 0 10px 10px 0; max-width: 120px; height: 60px" :src="companySetForm.logo" v-if="companySetForm.logo" />
                    <el-button type="plain" icon="el-icon-plus" @click="setCompany('upload-logo')">{{ companySetForm.logo ? "更换图片" : "选择图片" }}</el-button>
                </el-form-item>
                 <el-form-item label="统一社会信用代码：">
                    <el-input ref="xydm" v-model="companySetForm.xydm" style="width: 480px" placeholder="请输入" :maxlength="100" :readonly="loading" @change="setCompany('validate')"></el-input>
                </el-form-item>
                <el-form-item label="企业/项目名称：" required>
                    <el-input ref="companySetFormName" v-model="companySetForm.name" style="width: 480px" placeholder="请输入" :maxlength="100" :readonly="loading" @change="setCompany('validate')"></el-input>
                </el-form-item>
                <el-form-item label="企业/项目简介：">
                    <el-input type="textarea" v-model="companySetForm.desc" style="width: 480px" placeholder="请输入" :rows="2" resize="none" :readonly="loading" @change="setCompany('validate')"></el-input>
                </el-form-item>
                <el-form-item label="所在地址：" required>
                    <el-select v-model="companySetForm.province.id" style="margin-right: 10px; width: 160px" placeholder="省份" @change="setCompany('validate')">
                        <el-option v-for="data in provinces" :key="data.id" :label="data.name" :value="data.id"></el-option>
                    </el-select>
                    <el-select v-model="companySetForm.city.id" style="margin-right: 10px; width: 150px" placeholder="城市" clearable @change="setCompany('validate')">
                        <template v-for="data in citys">
                            <el-option :key="data.id" :label="data.name" :value="data.id" v-if="data.province.id === companySetForm.province.id"></el-option>
                        </template>
                    </el-select>
                    <el-select v-model="companySetForm.county.id" style="width: 150px" placeholder="县区" clearable @change="setCompany('validate')">
                        <template v-for="data in countys">
                            <el-option :key="data.id" :label="data.name" :value="data.id" v-if="data.city.id === companySetForm.city.id"></el-option>
                        </template>
                    </el-select>
                    <div style="margin-top: 10px"></div>
                    <el-input v-model="companySetForm.location.address" style="width: 480px" placeholder="详细地址" :maxlength="100" :readonly="loading" @change="setCompany('validate')"></el-input>
                </el-form-item>
                <el-form-item label="地址坐标：">
                    <el-input v-model="companySetForm.location.coord" style="width: 392px" placeholder="请输入" :readonly="loading" @change="setCompany('validate')"></el-input>
                    <el-tag style="margin-left: 10px" disable-transitions>
                        <span>坐标拾取</span>
                        <a style="position: absolute; top: 0; left: 0; width: 100%; height: 100%" href="https://lbs.qq.com/tool/getpoint/index.html" target="_blank"></a>
                    </el-tag>
                </el-form-item>
                <el-form-item label="法定代表人：">
                    <el-input v-model="companySetForm.owner" style="width: 480px" placeholder="请输入" :maxlength="100" :readonly="loading" @change="setCompany('validate')"></el-input>
                </el-form-item>
                <el-form-item label="企业/项目规模：">
                    <el-select v-model="companySetForm.size" style="width: 480px" placeholder="请选择" @change="setCompany('validate')">
                        <el-option v-for="data in env.companySizes" :key="data.id" :label="data.name" :value="data.value"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="所属行业：" required>
                    <el-cascader
                        v-model="companySetForm.industryIds"
                        :options="industryTreeData"
                        :props="{label:'name',value:'id'}"
                    />
                </el-form-item>
                <el-form-item label="企业性质：">
                    <el-select v-model="companySetForm.qyxz" style="width: 480px" placeholder="请选择" @change="setCompany('validate')">
                        <el-option key="0" label="国有控股" value="国有控股"></el-option>
                        <el-option key="1" label="民营企业" value="民营企业"></el-option>
                        <el-option key="2" label="外资企业" value="外资企业"></el-option>
                    </el-select>
                </el-form-item>
                 <el-form-item label="服务小组：">
                    <el-select v-model="companySetForm.fwxz" style="width: 480px" placeholder="请选择" @change="setCompany('validate')">
                        <el-option key="17" label="市县自主调研" value="市县自主调研"></el-option>

                        <el-option key="0" label="第一组" value="第一组"></el-option>
                        <el-option key="1" label="第二组" value="第二组"></el-option>
                        <el-option key="2" label="第三组" value="第三组"></el-option>
                        <el-option key="3" label="第四组" value="第四组"></el-option>
                        <el-option key="4" label="第五组" value="第五组"></el-option>
                        <el-option key="5" label="第六组" value="第六组"></el-option>
                        <el-option key="6" label="第七组" value="第七组"></el-option>
                        <el-option key="7" label="第八组" value="第八组"></el-option>
                        <el-option key="8" label="第九组" value="第九组"></el-option>
                        <el-option key="9" label="第十组" value="第十组"></el-option>
                        <el-option key="10" label="第十一组" value="第十一组"></el-option>
                        <el-option key="11" label="第十二组" value="第十二组"></el-option>
                        <el-option key="12" label="第十三组" value="第十三组"></el-option>
                        <el-option key="13" label="第十四组" value="第十四组"></el-option>
                        <el-option key="14" label="第十五组" value="第十五组"></el-option>
                        <el-option key="15" label="第十六组" value="第十六组"></el-option>
                        <el-option key="16" label="第十七组" value="第十七组"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="所属分类：">
                    <el-select v-model="companySetForm.tag.id" style="width: 480px" placeholder="请选择" @change="setCompany('validate')">
                        <el-option v-for="data in tags" :key="data.id" :label="data.name" :value="data.id"></el-option>
                    </el-select>
                </el-form-item>
<!--                <el-form-item label="主管工作队：">-->
<!--                    <el-tag v-for="dept in companySetForm.depts" :key="dept.id" style="margin: 0 10px 10px 0" disable-transitions>{{ dept.name }}</el-tag>-->
<!--                    <div v-if="companySetForm.depts.length > 0"></div>-->
<!--                    <el-button type="plain" icon="el-icon-plus" @click="setCompany('pick-dept-start')">选择工作队</el-button>-->
<!--                    <el-button type="plain" icon="el-icon-delete" @click="setCompany('clear-depts')" v-if="companySetForm.depts.length > 0">清空</el-button>-->
<!--                </el-form-item>-->
                <el-form-item label="审核状态：" v-if="canApprove">
                    <el-select v-model="companySetForm.status" style="width: 160px" placeholder="请选择" @change="setCompany('validate')">
                        <el-option v-for="data in env.companyStatus" :key="data.id" :label="data.name" :value="data.value"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" icon="el-icon-check" @click="setCompany('submit')">保存</el-button>
                    <el-button type="plain" icon="el-icon-close" @click="setCompany('end')">放弃</el-button>
                </el-form-item>
            </el-form>
        </comp-dialog>
        <comp-dialog title="选择工作队" width="720px" height="80vh" ref="deptPicker">
            <comp-depts style="height: 100%" ref="deptPickerList" v-if="companySetForm">
                <template #body="scope">
                    <el-button type="primary" size="mini" icon="el-icon-check" @click.stop="setCompany('pick-dept-end', scope.data)" v-if="(scope.data.type === 'team' || scope.data.type === 'office') && scope.data.city.id === companySetForm.city.id && companySetForm.city.id">选择</el-button>
                </template>
                <template #foot="scope">
                    <el-button type="danger" size="small" icon="el-icon-close" @click="setCompany('pick-dept-end')">放弃</el-button>
                </template>
            </comp-depts>
        </comp-dialog>
        <comp-dialog title="添加服务专员" width="360px" ref="companyHolder">
            <el-form size="small" label-width="84px" @submit.native.prevent v-if="companyHolder">
                <el-form-item label="用户：" required>
                    <el-tag style="margin: 0 10px 10px 0" disable-transitions v-if="companyHolder.client.id">{{ companyHolder.client.name }}</el-tag>
                    <div v-if="companyHolder.client.id"></div>
                    <el-button type="plain" icon="el-icon-plus" @click="addCompanyHolder('pick-client-start')">{{ companyHolder.client.id ? "更换用户" : "选择用户" }}</el-button>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" icon="el-icon-check" @click="addCompanyHolder('submit')">添加</el-button>
                    <el-button type="plain" icon="el-icon-close" @click="addCompanyHolder('end')">放弃</el-button>
                </el-form-item>
            </el-form>
        </comp-dialog>
        <comp-dialog title="添加联系人" ref="companyStaff">
            <el-form size="small" label-width="84px" style="margin-right: 20px" @submit.native.prevent v-if="companyStaff">
                <el-form-item label="用户：" required>
                    <el-tag style="margin: 0 10px 10px 0; max-width: 240px" disable-transitions v-if="companyStaff.client.id">{{ companyStaff.client.name }}</el-tag>
                    <div v-if="companyStaff.client.id"></div>
                    <el-button type="plain" icon="el-icon-plus" @click="addCompanyStaff('pick-client-start')">{{ companyStaff.client.id ? "更换用户" : "选择用户" }}</el-button>
                </el-form-item>
                <el-form-item label="职务：">
                    <el-input v-model="companyStaff.duty" style="width: 240px" placeholder="请输入" :maxlength="100" :readonly="loading" @change="addCompanyStaff('validate')"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" icon="el-icon-check" @click="addCompanyStaff('submit')">添加</el-button>
                    <el-button type="plain" icon="el-icon-close" @click="addCompanyStaff('end')">放弃</el-button>
                </el-form-item>
            </el-form>
        </comp-dialog>
        <comp-dialog title="选择服务专员" width="80vw" height="80vh" ref="clientHolderPicker">
            <comp-clients style="height: 100%" ref="clientHolderPickerList" role="holder">
                <template #body="scope">
                    <el-button type="primary" size="mini" icon="el-icon-check" @click.stop="addCompanyHolder('pick-client-end', scope.data)">选择</el-button>
                </template>
                <template #foot="scope">
                    <el-button type="danger" size="small" icon="el-icon-close" @click="addCompanyHolder('pick-client-end')">放弃</el-button>
                </template>
            </comp-clients>
        </comp-dialog>
        <comp-dialog title="选择企业人员" width="80vw" height="80vh" ref="clientStaffPicker">
            <comp-clients style="height: 100%" ref="clientStaffPickerList" role="staff">
                <template #body="scope">
                    <el-button type="primary" size="mini" icon="el-icon-check" @click.stop="addCompanyStaff('pick-client-end', scope.data)">选择</el-button>
                </template>
                <template #foot="scope">
                    <el-button type="danger" size="small" icon="el-icon-close" @click="addCompanyStaff('pick-client-end')">放弃</el-button>
                </template>
            </comp-clients>
        </comp-dialog>
    </div>
</template>

<script>
    import mixin from "../mixin";
    import { string, int, float, deepCopy, toMagicImgURL, selectFile, cache } from "../util";
    import treeData from '@/plugins/treeData'
    import {getSysIndustryList} from '@/api/industry'
    export default {
        name: "page-corp-company",
        title: "企业/项目详情",
        nodes: ["/menu/corp"],
        childs: [],
        mixins: [mixin],
        computed: {
            canApprove() {
                if(this.plugins.user?.profile?.depments?.[0]?.dept?.city?.id){
                    return this.plugins.user?.profile?.depments?.[0]?.dept?.city?.id == this.companySetForm?.city?.id;
                }
                return true
            },
        },
        data: () => ({
            loading: false,
            companyId: "",
            company: null,
            companySetForm: null,
            companyHolder: null,
            companyStaff: null,
            provinces: [],
            citys: [],
            countys: [],
            tags: [],
            industryTreeData:[]
        }),
        methods: {
            action(name, data) {
                if (this.loading) return;
                if (name === "company-desc") {
                    if (data) {
                        this.$refs.companyDesc.init();
                        this.$nextTick(() => this.$refs.companyDescEditor.init());
                    } else {
                        this.$refs.companyDescEditor.destroy();
                        this.$refs.companyDesc.close();
                    }
                }
            },
            setCompany(action, data) {
                if (this.loading) return;
                let form = this.companySetForm;
                let provinces = this.provinces = this.plugins.user.provinces;
                let citys = this.citys = this.plugins.user.citys;
                let countys = this.countys = this.plugins.user.countys;
                let tags = this.tags;
                if (!action || action === "start") {
                    getSysIndustryList({
                        id_exp:[
                            { exp: "in", value: "202316872581980012,202216420729294108,202216575009104433,202316872582170014" ,parameterType:'Long'},
                        ],
                    }).then(res=>{
                        console.log('getSysIndustryList',res)
                        if(res?.data?.list){
                            this.industryTreeData = treeData.arrayToTree(res.data.list,'id','parentId','')
                        }
                    })
                    this.loading = true;
                    this.plugins.user.call(async () => {
                        if (tags.length > 0) return { code: 0 };
                        let res = await this.plugins.user.getCompanyOfTags({ linage: 100, page: 1 });
                        if (res.code === 0) this.tags = res.data.list;
                        return res;
                    }).then((res) => {
                        this.loading = false;
                        if (res.code === 0) {
                            this.companySetForm = deepCopy(this.company);
                            this.companySetForm.industryIds = this.companySetForm?.corpIdSysIndustryList?.sort((a,b)=>a.parentId>b.parentId?1:-1)?.map(x=>x.id)
                            console.log('industryIds',this.companySetForm.industryIds)
                            this.setCompany("validate");
                            this.$refs.companySetForm.init();
                            this.$nextTick(() => this.$refs.companySetFormName.focus());
                        } else {
                            this.plugins.modal.toast("加载失败<br>" + res.code + "：" + res.msg, "error");
                        }
                    });
                } else if (action === "validate") {
                    let error = "";
                    form.name = string(form.name).trim();
                    error = error || (form.name ? "" : "请输入企业/项目名称！");
                    error = error || (form.industryIds?.length > 0 ? "" : "所属行业必填！");
                    console.log(form.industry.name);

                    // error = error || (form.xydm ? "" : "请输入统一社会信用代码！");
                    form.xydm = string(form.xydm).trim();

                    form.desc = string(form.desc);
                    form.province.id = string(() => provinces.find((province) => province.id === form.province.id).id);
                    form.city.id = string(() => citys.find((city) => city.id === form.city.id && city.province.id === form.province.id).id);
                    form.county.id = string(() => countys.find((county) => county.id === form.county.id && county.city.id === form.city.id).id);
                    error = error || (form.province.id && form.city.id && form.county.id ? "" : "请完善所在地址！");
                    form.location.address = string(form.location.address).trim();
                    form.location.coord = string(form.location.coord).trim();
                    form.location.lng = Math.min(Math.max(float(form.location.coord.split(",")[1], 6), 0), 180);
                    form.location.lat = Math.min(Math.max(float(form.location.coord.split(",")[0], 6), 0), 90);
                    form.location.coord = form.location.lng > 0 && form.location.lat > 0 ? form.location.lat + "," + form.location.lng : "";
                    form.owner = string(form.owner).trim();
                    form.fwxz = string(form.fwxz).trim();
                    form.qyxz = string(form.qyxz).trim();

                    form.industry.name = string(form.industry.name).trim();
                    if (data) this.plugins.modal.toast(error, "error");
                    return !error;
                } else if (action === "upload-logo") {
                    if (!data) return selectFile("image/*").then((file) => {
                        if (file.size > 5 * 1048576) this.plugins.modal.toast("图片过大，不能大于5MB哦！请重新选择。", "error");
                        else this.setCompany(action, file);
                    });
                    let timer = null;
                    let progress = (event) => timer = clearTimeout(timer) || setTimeout(() => this.plugins.modal.toast("上传进度：" + event.percent + "%", "info"), 200);
                    this.loading = true;
                    this.plugins.user.uploadFile(data, "image", progress).then((res) => {
                        this.loading = false;
                        if (res.code === 0) {
                            form.logo = toMagicImgURL(res.data.value, 120, 120);
                            this.setCompany("validate");
                        } else {
                            this.plugins.modal.alert("图片上传失败", res.code + "：" + res.msg, "error");
                        }
                    });
                } else if (action === "pick-dept-start") {
                    this.$refs.deptPicker.init();
                    this.$nextTick(() => this.$refs.deptPickerList.init());
                } else if (action === "pick-dept-end") {
                    if (data && form.depts.findIndex((dept) => dept.id === data.id) === -1) form.depts.push(data);
                    this.setCompany("validate");
                    this.$refs.deptPicker.close();
                } else if (action === "clear-depts") {
                    form.depts.splice(0);
                    this.setCompany("validate");
                } else if (action === "submit") {
                    if (!this.setCompany("validate", true)) return;
                    this.loading = true;
                    this.plugins.user.setCompany(form).then((res) => {
                        this.loading = false;
                        if (res.code === 0) {
                            this.plugins.modal.toast("保存成功！", "success");
                            this.setCompany("end");
                            this.init();
                        } else {
                            this.plugins.modal.alert("保存失败", res.code + "：" + res.msg, "error");
                        }
                    });
                } else if (action === "end") {
                    this.$refs.companySetForm.close();
                }
            },
            addCompanyHolder(action, data) {
                if (this.loading) return;
                let company = this.company;
                let form = this.companyHolder;
                if (!action || action === "start") {
                    this.companyHolder = this.plugins.user.formatCompanyHolder();
                    this.companyHolder.company.id = company.id;
                    this.addCompanyHolder("validate");
                    this.$refs.companyHolder.init();
                } else if (action === "validate") {
                    let error = "";
                    error = error || (form.client.id ? "" : "请选择用户！");
                    if (data) this.plugins.modal.toast(error, "error");
                    return !error;
                } else if (action === "pick-client-start") {
                    this.$refs.clientHolderPicker.init();
                    this.$nextTick(() => this.$refs.clientHolderPickerList.init());
                } else if (action === "pick-client-end") {
                    if (data) form.client = deepCopy(data);
                    this.$refs.clientHolderPicker.close();
                    this.addCompanyHolder("validate");
                } else if (action === "submit") {
                    if (!this.addCompanyHolder("validate", true)) return;
                    this.loading = true;
                    this.plugins.user.addCompanyHolder(form.company, form.client, form).then((res) => {
                        this.loading = false;
                        if (res.code === 0) {
                            this.plugins.modal.toast("设置成功！", "success");
                            this.addCompanyHolder("end");
                            this.init();
                        } else {
                            this.plugins.modal.alert("设置失败", res.code + "：" + res.msg, "error");
                        }
                    });
                } else if (action === "end") {
                    this.$refs.companyHolder.close();
                }
            },
            delCompanyHolder(holder) {
                if (this.loading) return;
                let content = " <span style='color:red;'>" + holder.client.name + "</span> 吗？";
                this.plugins.modal.alert("删除确认", "确定删除" + content, "warning", ["确定删除", "再想想"]).then((ok) => {
                    if (!ok) return;
                    this.loading = true;
                    this.plugins.user.delCompanyHolder(holder).then((res) => {
                        this.loading = false;
                        if (res.code === 0) {
                            this.plugins.modal.toast("删除成功！", "success");
                            this.init();
                        } else {
                            this.plugins.modal.alert("删除失败", res.code + "：" + res.msg, "error");
                        }
                    });
                });
            },
            addCompanyStaff(action, data) {
                if (this.loading) return;
                let company = this.company;
                let form = this.companyStaff;
                if (!action || action === "start") {
                    this.companyStaff = this.plugins.user.formatCompanyStaff();
                    this.companyStaff.company.id = company.id;
                    this.addCompanyStaff("validate");
                    this.$refs.companyStaff.init();
                } else if (action === "validate") {
                    let error = "";
                    error = error || (form.client.id ? "" : "请选择用户！");
                    form.duty = string(form.duty).trim();
                    if (data) this.plugins.modal.toast(error, "error");
                    return !error;
                } else if (action === "pick-client-start") {
                    this.$refs.clientStaffPicker.init();
                    this.$nextTick(() => this.$refs.clientStaffPickerList.init());
                } else if (action === "pick-client-end") {
                    if (data) form.client = deepCopy(data);
                    this.$refs.clientStaffPicker.close();
                    this.addCompanyStaff("validate");
                } else if (action === "submit") {
                    if (!this.addCompanyStaff("validate", true)) return;
                    this.loading = true;
                    this.plugins.user.addCompanyStaff(form.company, form.client, form).then((res) => {
                        this.loading = false;
                        if (res.code === 0) {
                            this.plugins.modal.toast("添加成功！", "success");
                            this.addCompanyStaff("end");
                            this.init();
                        } else {
                            this.plugins.modal.alert("添加失败", res.code + "：" + res.msg, "error");
                        }
                    });
                } else if (action === "end") {
                    this.$refs.companyStaff.close();
                }
            },
            delCompanyStaff(staff) {
                if (this.loading) return;
                let content = " <span style='color:red;'>" + staff.client.name + "</span> 吗？";
                this.plugins.modal.alert("删除确认", "确定删除" + content, "warning", ["确定删除", "再想想"]).then((ok) => {
                    if (!ok) return;
                    this.loading = true;
                    this.plugins.user.delCompanyStaff(staff).then((res) => {
                        this.loading = false;
                        if (res.code === 0) {
                            this.plugins.modal.toast("删除成功！", "success");
                            this.init();
                        } else {
                            this.plugins.modal.alert("删除失败", res.code + "：" + res.msg, "error");
                        }
                    });
                });
            },
            destroy() {
                if (this.loading) return;
                return true;
            },
            init() {
                if (this.loading) return;
                let query = this.$route.query;
                let company = null;
                this.loading = true;
                this.companyId = query.companyId;
                this.company = cache(query.companyId);
                this.$root.$refs.navbar.init();
                this.plugins.user.call(async () => {
                    let res = await this.plugins.user.init();
                    if (res.code === 0) { }
                    return res;
                }, async () => {
                    if (this.access(this.$route.name)) return { code: 0 };
                    return this.env.xhrErrors.find((error) => error.code === 4);
                }, async () => {
                    let res = await this.plugins.user.getCompany(query.companyId);
                    console.log(res);
                    if (res.code === 0) company = res.data;
                    return res;
                }).then((res) => {
                    this.loading = false;
                    this.$root.$refs.navbar.init();
                    if (res.code === 0) {
                        this.company = cache(query.companyId, company);
                        this.company.corpIdSysIndustryList = this.company?.corpIdSysIndustryList?.sort((a,b)=>a.parentId>b.parentId?1:-1)
                    } else if (res.code === 2) {
                        this.$root.$refs.navbar.login();
                    } else {
                        this.plugins.modal.alert("页面加载失败", res.code + "：" + res.msg, "error").then(() => this.$router.replace("/corp/companys"));
                    }
                });
            },
        },
    };
</script>

<style lang="scss">
    .page-corp-company {
        overflow: hidden;
    }
    .name{
        width: 160px !important;
    }
</style>
